package org.lkp.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.lkp.reggie.pojo.entity.User;
import org.lkp.reggie.response.R;
import org.lkp.reggie.service.UserService;
import org.lkp.reggie.utils.SMSUtils;
import org.lkp.reggie.utils.ValidateCodeUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;

import java.util.regex.Pattern;

@Slf4j
@RestController
@RequestMapping("/user")
@RequiredArgsConstructor
public class UserController {
    private final UserService userService;

    // 手机号码正则表达式，可根据实际情况调整
    private static final Pattern PHONE_PATTERN = Pattern.compile("^1[3-9]\\d{9}$");

    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session) {

        String phone = user.getPhone();
        // 2. 简单的安全校验，可根据情况决定是否保留
        if (!PHONE_PATTERN.matcher(phone).matches()) {
            log.error("手机号码格式不符合基本规则: {}", phone);
            return R.error("手机号码格式有误，请检查后重试");
        }

        try {
            // 3. 生成验证码
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            log.info("为手机号码 {} 生成的验证码是: {}", phone, code);
            // 4. 发送短信
//            SMSUtils.sendMessage("阿里云短信测试", "SMS_154950909", phone, code);

            // 5. 将验证码存入 session
            session.setAttribute(phone, code);

            log.info("手机号码 {} 的短信验证码发送成功", phone);
            return R.success("短信发送成功！");
        } catch (Exception e) {
            // 6. 异常处理
            log.error("为手机号码 {} 发送短信验证码时出现异常: {}", phone, e.getMessage(), e);
            return R.error("短信发送失败，请稍后重试！");
        }
    }

    @PostMapping("/login")
    public R<User> login(@RequestBody Map map,HttpSession session) {
        log.info(map.toString());
        String phone = map.get("phone").toString();
        Object codeInSession = session.getAttribute(phone);
        if (codeInSession!=null){
            LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(User::getPhone, phone);
            User user = userService.getOne(wrapper);
            if (user == null) {
                user = new User();
                user.setPhone(phone);
                user.setStatus(1);
                userService.save(user);
            }
            session.setAttribute("user",user.getId());
            return R.success(user);
        }


        return R.error("登录失败!");
    }

}